package com.linjiang.design.flyweight;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//享元模式
//运用共享技术有效地支持大量细粒度的对象
public class FlyweightTest {
    public static void main(String[] args) {
        TreeFactory treeFactory = new TreeFactory();
        TreeNode treeNode = new TreeNode(0,4, treeFactory.getTree("苹果树", "红色"));
        TreeNode treeNode2 = new TreeNode(0,5, treeFactory.getTree("苹果树", "红色"));
    }
}

class TreeNode{

    private int x;
    private int y;
    private Tree tree;

    public TreeNode(int x, int y, Tree tree) {
        this.x = x;
        this.y = y;
        this.tree = tree;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public Tree getTree() {
        return tree;
    }

    public void setTree(Tree tree) {
        this.tree = tree;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "x=" + x +
                ", y=" + y +
                ", tree=" + tree +
                '}';
    }
}

//树工厂
class TreeFactory{
    private static Map<String, Tree> map = new ConcurrentHashMap<>();

    public static Tree getTree(String name, String data){
        if (map.containsKey(name)){
            return map.get(name);
        }

        //没有则创建
        Tree tree = new Tree(name, data);
        map.put(name, tree);
        return tree;
    }
}
class Tree{
    private final String name;
    private final String data;

    public Tree(String name, String data) {
        System.out.println("创建树======>name："+name+",data: "+data);
        this.name = name;
        this.data = data;
    }

    public String getName() {
        return name;
    }

    public String getData() {
        return data;
    }

/*    @Override
    public String toString() {
        return "Tree{" +
                "name='" + name + '\'' +
                ", data='" + data + '\'' +
                '}';
    }*/
}
